
package com.imooc.security.order;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @author wangyouliang
 */
@RestController
@RequestMapping("/orders")
@Slf4j
public class OrderController {

    /**
     * OAuth2RestTemplate 默认将当前收到的令牌，放在发送请求的请求头里。
     */
    @Autowired
	private OAuth2RestTemplate restTemplate;

    @PostMapping
    @PreAuthorize("hasRole('ROLE_ADMIN')")
//    @SentinelResource(value = "createOrder", blockHandler = "doOnBlock")
    public OrderInfo create(@RequestBody OrderInfo info, @AuthenticationPrincipal String username) throws InterruptedException {
        log.info("user is " + username);
//		PriceInfo price = restTemplate.getForObject("http://localhost:9060/prices/"+info.getProductId(), PriceInfo.class);
//		log.info("price is "+price.getPrice());
//        throw new RuntimeException("haha, test");
        Thread.sleep(RandomUtils.nextInt(100, 1000));
        return info;
    }

    public OrderInfo doOnBlock(@RequestBody OrderInfo info, @AuthenticationPrincipal String username, BlockException exception) {
        log.info("blocked by " + exception.getClass().getSimpleName());
        return info;
    }

    @GetMapping("/{id}")
    @SentinelResource(value = "getOrder")
    public OrderInfo getInfo(@PathVariable Long id, @AuthenticationPrincipal String username) {
        log.info("user is " + username);
        log.info("orderId is " + id);
        OrderInfo info = new OrderInfo();
        info.setId(id);
        info.setProductId(id * 5);
        return info;
    }

}
